<!--
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-06-20 14:24:27
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-10-27 09:50:29
 * @FilePath: \project_keep\keep_motion_manger\src\views\login\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="login">
      <div class="login-title">Keep后台管理系统</div>
      <el-form :model="form" :rules="rules" ref="forms" class="login-form" label-width="120px">
        <el-form-item label="账号" prop="userName">
            <el-input v-model="form.userName" size="large"/>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
            <el-input v-model="form.passWord" size="large"/>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
            <el-input v-model="form.code" size="large"/>
            <lintCode :options="captcha" ref="captchaRef" @click="refrechCode"/>
        </el-form-item>
      </el-form>
      <div class="login-tips">
        <el-checkbox v-model="rembPassword" label="记住密码" size="large"/>
        <el-link href="#" type="primary">忘记密码？</el-link>
      </div>
      <div class="login-btns">
        <el-button type="primary" @click="login">登录</el-button>
      </div>
      <div class="login-tips">
        <el-link href="/register" type="info">还没有账号? 注册</el-link>
      </div>
  </div>
</template>
<script setup>
import './index.css';

import {ref, reactive, onBeforeMount, watch} from 'vue';
import router from '@/router';
import { ElMessage } from 'element-plus';

import { authApi, menuApi } from '@/api';
import { adjustPath } from '@/utils';
import lintCode from '@/components/lintCode/index.vue';
import { usePathStore } from '@/stores/paths';


const formParam = {
    userName: '',
    passWord: '',
    code: '',
};
const captchaOptions = {
  width: 120,
  height: 40
};
const form = reactive(formParam);
const forms = ref(null);
const rembPassword = ref(true);
// lintCode
const captcha = ref(captchaOptions);
const captchaRef = ref(null);

// 自定义验证函数 - 检查用户名是否包含空格
const validateUsername = (rule, value, callback) => {
    if (value.includes(' ')) {
    callback(new Error('用户名不能包含空格'));
    } else {
    callback();
    }
};
// 自定义验证函数 - 校验 图形验证码
const validateCode = (rule, value, callback) => {
    if (!captchaRef.value.validate(value)) {
        callback(new Error('验证码错误'));
    } else {
        callback();
    }
};
const rules = reactive({
    userName: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' },
        { validator: validateUsername, trigger: 'blur' }
    ],
    passWord: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, message: '密码长度至少为 5 个字符', trigger: 'blur' },
    ],
    code: [
        { required: true, message: '请输入验证码', trigger: 'blur' },
        { validator: validateCode, trigger: 'blur' }
    ]
});

// watch
watch(rembPassword, (newValue) => {
  localStorage.setItem('rembPassword', newValue);
  // 重置
  if(newValue) forms.value.resetFields();
  else {
    localStorage.removeItem('userName');
    localStorage.removeItem('passWord');
  }
});

onBeforeMount(() => {
  // 账号密码
  const tempBool = localStorage.getItem('rembPassword') === 'true'
  if(!tempBool) rembPassword.value = tempBool;
  else {
    form.userName = localStorage.getItem('userName');
    form.passWord = localStorage.getItem('passWord');
  } 
});
// 点击刷新验证码
const refrechCode = () => {
    captchaRef.value.refresh();
};

const login = () => {
  forms.value.validate(async (valid, fields) => {
    if (valid) {
      if(rembPassword) {
        localStorage.setItem('userName', form.userName);
        localStorage.setItem('passWord', form.passWord);
      }
      const res = await authApi.login(form);
      if(res.code >203){
        ElMessage.error(res.msg);
        return;
      }
      sessionStorage.setItem("role", res.data.role);
      sessionStorage.setItem("roleName", res.data.role_name);
      sessionStorage.setItem("name", res.data.nickname);
      sessionStorage.setItem("token", res.data.token);
      ElMessage.success('登录成功');

      // 待填充 权限校验

      // 登录成功后，获取菜单路径
      const pRes = await menuApi.getPath();
      if(pRes.code === 200) {
        const paths = adjustPath(pRes.data.rows);
        usePathStore().setPath(paths);
        sessionStorage.setItem('menuPath', JSON.stringify(paths));
        router.push({name: 'home'});
      }

    }
  });
};
</script>